<template>
  <div>
    <!-- 表单部分 ----------------------------------------->
      <div class="video_form">
        <div>
            <el-input v-model="searchText" placeholder="输入视频名称"></el-input>
            <el-button type="primary" @click="toSearch">查询</el-button>
        </div>
        <div>
          <el-button type="success" @click="toOpen">添加</el-button>
        </div>
      </div>
      <!-- 视频添加弹出层位置 -->
      <el-dialog width="50%" :title="title" :visible.sync="videoFlag">
        <el-form label-width="100px" :model="addObj"
        :rules="rules" ref="videoForm">
          <el-form-item label="视频上传：" >
            <div class="myupload">
                  <!-- 隐藏的原生文件框 -->
                 <input ref="myfile" type="file" style="display:none;" @change="uploadVieo">

                <el-input disabled v-model="addObj.Vurl"></el-input>
                <el-button type="primary" @click="toup">添加视频</el-button>
            </div>
          </el-form-item>
          <el-form-item label="视频名称：" prop="Vname">
               <el-input v-model="addObj.Vname"></el-input>
          </el-form-item>
            <el-form-item label="视频时长：" prop="Vtime">
               <el-input v-model="addObj.Vtime"></el-input>
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button type="success" @click="toAddVideo">确定</el-button>
           <el-button>取消</el-button>
        </template>
      </el-dialog>
      <!-- 表格部分 ------------------------------------->
      <div class="video_table">
            <table-title icon="el-icon-s-grid" title="视频列表"></table-title>
            <el-table border stripe :data="Vlist">
              <el-table-column label="视频名称" prop="Vname"></el-table-column>
               <el-table-column label="绑定课程" prop="Vstate"></el-table-column>
                <el-table-column label="视频时长" prop="mytime"></el-table-column>
                 <el-table-column label="发布日期" prop="createAt"></el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <div>
                        <el-link v-if="!btnCtrl" type="primary"
                        @click="toEdit(scope.row)">编辑</el-link>
                         <el-link v-if="!btnCtrl"  type="danger"
                          @click="toDel(scope.row.ID)">删除</el-link>
                          <el-button v-if="btnCtrl" type="primary"
                          @click="toAddDirVideo(scope.row._id)">添加</el-button>
                      </div>
                    </template>
                  </el-table-column>
            </el-table>
            <el-pagination background 
            :current-page="pageStart"
            :total="total"
            @current-change="pageChange"
            :page-size="pageSize">
            </el-pagination>
      </div>
   
  </div>
</template>

<script>
import {uploadVideo,addVideoApi,VideoListApi,delVideoApi,editVideoApi} from '../../api/video'
import {addDirVideo} from '../../api/course'
export default {
  name: 'Vuepro2209Index',
  props:["btnCtrl"],
  data() {
    return {
      dir_id:"",//目录的_id
      title:"添加视频",
      editId:"",//当前正在编辑的视频id
      pageStart:1,
      videoFlag:false,//视频添加的弹出层
      searchText:"",//搜索字段
      pageStart:1,//当前页码
      videoList:[],//视频列表
      total:0,//视频总条数
      pageSize:3,//每页条数
      addObj:{
          Vurl:"",//上传成功返回的视频路径 
          Vname:"",//视频名称
          Vtime:"",//视频时长
      },
      rules:{
        Vname:[{required:true,message:"视频名称必填",trigger:'blur'}],
        Vtime:[{required:true,message:"视频时长必填",trigger:'blur'}]
      }
    };
  },
  computed:{ //计算属性
    Vlist(){ //处理后台返回的VideoList数据
        let arr=this.videoList.map((item,index)=>{
          // 视频时长  123
          item.mytime=`${parseInt(item.Vtime/60)}小时，${
            item.Vtime%60
          }分钟`
          // 创建时间 处理时间
          item.createAt=new Date(item.createAt).toLocaleString()
          return item 
        })
        return arr
    }
  },
  created(){
    this.getVideList();
    // 接收目录组件传来的_id
    this.$bus.$on('sendDirId',(val)=>{
      this.dir_id=val;
    })
  },
  mounted() {
    
  },

  methods: {
    async toAddDirVideo(_id){ //给目录下添加视频接口
      if(this.dir_id){
            let res=await addDirVideo({
              cid:this.$route.query._id,//课程_id
              _id:this.dir_id, //目录_id,
              Vid:_id //视频_id
            })
            console.log(res)
            this.$bus.$emit("sendList",res.data.data.list)
            if(res.data.success){
              this.$message.success("添加视频成功")
            }
      }else{
        this.$message.error("请先选择目录！")
      }

    },
    toEdit(row){ //点击编辑按钮  netword
      this.addObj.Vurl=row.Vurl;
      this.addObj.Vname=row.Vname;
      this.addObj.Vtime=row.Vtime;
      this.editId=row.ID;
      this.videoFlag=true;
      this.title="编辑视频"
    },
     toDel(ID){ //删除视频接口
          delVideoApi(ID).then(res=>{
            console.log(res)
            this.$message.success("删除视频成功")
            this.getVideList()//删除成功 获取列表
          })
    },
    toSearch(){ //搜索
        this.getVideList();//重新调用列表接口
        this.searchText=""//搜索完成清空输入框
    },
    pageChange(val){ //分页的change事件
      // val--当前页面
        this.pageStart=val; //改变当前页码
        this.getVideList();//重新调用列表接口
    },
   async  getVideList(){ //获取视频列表接口
      let res=await VideoListApi({
        searchText:this.searchText,
        pageStart:this.pageStart
      })
        this.videoList=res.data.data.list; //视频列表
        this.total=res.data.data.count;//数据总条数
        this.pageSize=res.data.data.pageSize;//每页条数
        console.log(res)
   },
    toOpen(){//点击添加弹出遮罩
      this.videoFlag=true;
          this.addObj.Vurl=""
          this.addObj.Vname=""
          this.addObj.Vtime=""
    },
    toup(){ //点击添加视频按钮 弹出文件上传框
       this.$refs.myfile.click()      
    },
    async uploadVieo(){ //文件上传框的change事件 
        // 准备好要发送的formdata数据
        let formdata=new FormData();//原生方法 存储上传文件数据包的对象
        // 获取文件上传的数据
        let files=this.$refs.myfile.files[0];
        console.log(files)
        var maxSize = 1073741824;//500mb
        if(files.size>maxSize/2){
          this.$message.error("上传的视频不能大于500Mb")
          return 
        }
        // formdata.append(随机key,文件数据包)
        // 将选择的文件数据包 放到formdata对象
        formdata.append(""+new Date().getTime(),files)
        // 将formdata对象 传给后台
        let res=await uploadVideo(formdata)
        if(res.data.success){
          this.$message.success('上传成功')
          this.addObj.Vurl=res.data.cacheName;//存储返回的数据
        }
        console.log(res)
    },
     toAddVideo(){ //添加和修改
        // 表单验证通过 在调用接口
      this.$refs.videoForm.validate().then( async ()=>{


          if(this.addObj.Vurl){  //判断是否上传了视频
            if(this.editId){ //如有编辑id 编辑视频
              this.addObj.ID=this.editId; //编辑需要的ID
              let EditRes=await editVideoApi(this.addObj)
              console.log(EditRes)
                this.$message.success("编辑成功")
            }else{ //添加视频
              let res=await addVideoApi(this.addObj)
              console.log(res)
              if(res.data.success){
                this.$message.success("视频添加成功")
              }
            }
               this.videoFlag=false;//关闭遮罩
                // 清空输入框
                this.addObj.Vurl=""
                this.addObj.Vname=""
                this.addObj.Vtime=""
                this.getVideList();
                this.title="添加视频"
                this.editId="";//清空编辑id
          }else{
            this.$message.error("请先上传视频！")
          }
      })
     
    }
  },
};
</script>
<style lang="less">
    .video_form{
      display:flex;
      justify-content:space-between;
      >div:nth-child(1){
             display:flex;
      }
    }
    .myupload{
        display:flex;
    }
 
</style>